package com.br.generateswingview.core;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.br.dnaklass.core.FamilyTree;
import com.br.generateswingview.annotations.Alias;

@SuppressWarnings("rawtypes")
public class GViewList<T> extends JDialog {
	private static final long serialVersionUID = 1L;
	private List<T> objects;
	private JTable table;

	public GViewList(List<T> object) {
		this.objects = object;
		table = new JTable();
		mountView();
	}

	private void mountView() {
		final Class klass = this.objects.get(0).getClass();
		this.setTitle("Lista " + klass.getSimpleName());
		this.setModal(true);

		List<Class> parents = FamilyTree.getParents(klass);
		List<String> columns = new ArrayList<String>();
		for (Class c : parents) {
			for (Field field : c.getDeclaredFields()) {
				if (field.isAnnotationPresent(Alias.class))
					columns.add(field.getAnnotation(Alias.class).value());
				else
					columns.add(field.getName());
			}
		}

		String[][] content = new String[objects.size() + 1][columns.size()];
		for (int i = 0; i < columns.size(); i++) {
			content[0][i] = columns.get(i);
		}
		for (int i = 0; i < objects.size(); i++) {
			T object = objects.get(i);
			int j = 0;
			for (Class parent : parents) {
				for (Field field : parent.getDeclaredFields()) {
					field.setAccessible(true);
					try {
						content[i + 1][j++] = String.class.cast(field
								.get(object) + " ");
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}

		DefaultTableModel model = new DefaultTableModel(content,
				columns.toArray(new String[columns.size()]));
		initFrame(columns.size(), objects.size());
		this.table.setModel(model);
		this.add(this.table);
	}

	private void initFrame(int countData, int countFields) {
		this.setResizable(false);

		int width = countFields * 50;
		width = width < 500 ? 500 : width;
		this.setSize(width, 30 * countData + 30);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}

}
